package com.example.text.controller;

import com.example.text.common.result.Result;
import com.example.text.common.result.ResultFactory;
import com.example.text.common.utils.StringUtils;
import com.example.text.entity.Notice;
import com.example.text.service.JotterArticleService;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@RestController
public class JotterController {
    @Autowired
    JotterArticleService jotterArticleService;

    @PostMapping("api/admin/content/article")
    public Result saveArticle(@RequestBody @Valid Notice article) {
        jotterArticleService.addOrUpdate(article);
        return ResultFactory.buildSuccessResult("保存成功");
    }

    @GetMapping("/api/article/{size}/{page}")
    public Result listArticles(@PathVariable("size") int size, @PathVariable("page") int page) {

        System.out.println("一页有："+size+"个数据");
        System.out.println("从第"+page+"个页开始");
        Page<Notice> pages = new Page<>(page,size);
        return ResultFactory.buildSuccessResult(jotterArticleService.selectJotterArticlePage(pages));
    }

    @DeleteMapping("/api/admin/content/article/{id}")
    public Result deleteArticle(@PathVariable("id") int id) {

        jotterArticleService.removeById(id);

        return ResultFactory.buildSuccessResult("删除成功");
    }

    @PostMapping("/api/admin/content/article/Deletes/{ids}")
    public  Result deleteArticles(@PathVariable("ids") String ids){

        String[] articleId=ids.split("\\,");
        jotterArticleService.removeByIds(Arrays.asList(articleId));
        return  ResultFactory.buildSuccessResult("批量删除成功");
    }

    @GetMapping("/api/article/{id}")
    public Result getOneArticle(@PathVariable("id") int id) {
        return ResultFactory.buildSuccessResult(jotterArticleService.selectById(id));
    }

    @CrossOrigin
    @PostMapping("/api/admin/new/covers")
    public String coversUpload(MultipartFile file) throws Exception {
        String folder = "E:/maven工程/text/src/main/resources/static/Images";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8081/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
